package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MarketMerchantCooperationStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantCooperationType;
import com.rockcent.mall.lib.dto.MarketMerchantCooperationRecordDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by HK on 16/9/14.
 */
@RestController
public class MarketMerchantCooperationRecordController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MarketMerchantCooperationRecordController.class);

    @Autowired
    private BaseUserHelper userHelper;
    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;
    @Autowired
    private MarketMerchantCooperationRecordRepository marketMerchantCooperationRecordRepository;
    @Autowired
    private MarketMerchantCooperationMessageRepository marketMerchantCooperationMessageRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * @api {get} /market/merchant/cooperation/record_page 商家合作管理 申请记录 分页
     * @apiGroup market_merchant_cooperation_record
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     *
     *
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     * @apiParam {String=WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")} status 状态
     * @apiParam {String} searchMerchantName 搜索:商家名称
     *
     * @apiSuccess {String} type 类型
     * @apiSuccess {String} status 状态 ALL("全部"),WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")
     * @apiSuccess {String} toMerchantName 目标商家名称
     *
     * @apiParam {String=WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")} status 状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "data": [
     *          {
     *              "id": 14,
     *              "dateCreated": "2016-09-14 15:39:14",
     *              "lastUpdated": "2016-09-14 15:39:14",
     *              "supplierMallId": 2,
     *              "supplierMerchantId": 3,
     *              "supplierMerchantName": "b2",
     *              "distributorMallId": 1,
     *              "distributorMerchantId": 1,
     *              "distributorMerchantName": "B1",
     *              "distributorMerchantIntro": "OE 好嘿劲",
     *              "distributorUserInfoRealName": "OE 只辣鸡",
     *              "distributorUserInfoMobile": "15920385185",
     *              "distributorUserInfoEmail": "oe@qq.com",
     *              "status": "WAIT"
     *          }
     *      ],
     *      "totalCount": 8,
     *      "totalPage": 1,
     *      "pageNo": 0,
     *      "pageSize": 10,
     *      "url": "/market/merchant/cooperation/record_page",
     *      "prevUrl": "/market/merchant/cooperation/record_page?pageNo=0&pageSize=10",
     *      "nextUrl": "/market/merchant/cooperation/record_page?pageNo=0&pageSize=10"
     *  }
     * }
     *
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_RECORD_PAGE, method = RequestMethod.GET)
    public JsonResult<PageResult<MarketMerchantCooperationRecordDto>> recordPage(MarketMerchantCooperationRecordDto marketMerchantCooperationRecordDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing<PageResult<MarketMerchantCooperationRecordDto>> doing = jsonResult -> {

            if (StringUtils.isBlank(marketMerchantCooperationRecordDto.getType())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationRecordDto.getType())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_TYPE_ALLOW,log);
                return;
            }
            if (!EnumUtils.isValidEnum(MarketMerchantCooperationStatus.class, marketMerchantCooperationRecordDto.getStatus())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_STATUS_ALLOW,log);
                return;
            }

            PageResult<MarketMerchantCooperationRecordDto> pageResult = marketMerchantCooperationRecordRepository.findPage(userInfoDto.merchant.getId(), marketMerchantCooperationRecordDto.getSearchMerchantName(), MarketMerchantCooperationStatus.valueOf(marketMerchantCooperationRecordDto.getStatus()),MerchantCooperationType.valueOf(marketMerchantCooperationRecordDto.getType()), this.getPage(marketMerchantCooperationRecordDto.getPageNo(), marketMerchantCooperationRecordDto.getPageSize()));
            pageResult.setUrl(Routes.MARKET_MERCHANT_COOPERATION_RECORD_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(userInfoDto,request,objectMapper, log);
    }

    /**
     * @api {get} /market/merchant/cooperation/record_info 商家合作管理 申请记录 信息
     * @apiGroup market_merchant_cooperation_record
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     *
     * @apiParam {Long} id id
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     *
     * @apiSuccess {String} type 类型
     * @apiSuccess {String=WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")} status 状态
     * @apiSuccess {String} toMerchantName 目标商家名称
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功",
     *      "data":{
     *          "id": 1,
     *          "dateCreated": "2016-09-12 20:15:20",
     *          "lastUpdated": "2016-09-12 20:15:20",
     *          "version": 1,
     *          "fromMerchantId": 1,
     *          "toMerchantId": 2,
     *          "toMerchantName":"B1",
     *          "type": "DISTRIBUTOR",
     *          "status": "PASS"
     *      }
     * }
     *
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_RECORD_INFO, method = RequestMethod.GET)
    public JsonResult<MarketMerchantCooperationRecord> recordInfo(MarketMerchantCooperationRecordDto marketMerchantCooperationRecordDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing<MarketMerchantCooperationRecord> doing = jsonResult -> {
            if (marketMerchantCooperationRecordDto.getId() == null) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (StringUtils.isBlank(marketMerchantCooperationRecordDto.getType())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationRecordDto.getType())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_TYPE_ALLOW,log);
                return;
            }

            MarketMerchantCooperationRecord marketMerchantCooperationRecord = null;
            if (MerchantCooperationType.DISTRIBUTOR == MerchantCooperationType.valueOf(marketMerchantCooperationRecordDto.getType())) {
                marketMerchantCooperationRecord = marketMerchantCooperationRecordRepository.findByIdAndSupplierMerchantId(marketMerchantCooperationRecordDto.getId(), userInfoDto.merchant.getId());
            } else if (MerchantCooperationType.SUPPLIER == MerchantCooperationType.valueOf(marketMerchantCooperationRecordDto.getType())) {
                marketMerchantCooperationRecord = marketMerchantCooperationRecordRepository.findByIdAndDistributorMerchantId(marketMerchantCooperationRecordDto.getId(), userInfoDto.merchant.getId());
            }

            jsonResult.data = marketMerchantCooperationRecord;
        };
        return doing.go(userInfoDto,request,objectMapper, log);
    }


    /**
     * @api {post} /market/merchant/cooperation/record_audit 商家合作管理 申请记录 审核
     * @apiGroup market_merchant_cooperation_record
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id 记录id
     * @apiParam {String=PASS("审核通过"),REFUSE("拒绝")} status 状态
     *
     * @apiSuccess {String} type 类型
     * @apiSuccess {String} status 状态 WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")
     * @apiSuccess {String} toMerchantName 目标商家名称
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     * }
     *
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_RECORD_AUDIT, method = RequestMethod.POST)
    @Transactional
    public JsonResult recordAudit(@RequestBody MarketMerchantCooperationRecordDto marketMerchantCooperationRecordDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing<PageResult<MarketMerchantCooperationRecordDto>> doing = jsonResult -> {

            if (marketMerchantCooperationRecordDto.getId() == null) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (StringUtils.isBlank(marketMerchantCooperationRecordDto.getStatus())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_STATUS_IS_NOT_NULL,log);
                return;
            }
            if (!EnumUtils.isValidEnum(MarketMerchantCooperationStatus.class, marketMerchantCooperationRecordDto.getStatus())) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_STATUS_ALLOW,log);
                return;
            }
            MarketMerchantCooperationRecord marketMerchantCooperationRecord = marketMerchantCooperationRecordRepository.findByIdAndSupplierMerchantId(marketMerchantCooperationRecordDto.getId(), userInfoDto.merchant.getId());
            if (marketMerchantCooperationRecord == null) {
                jsonResult.remind(MarketMerchantCooperationRecord.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (marketMerchantCooperationRecord.getStatus() != MarketMerchantCooperationStatus.WAIT) {
                jsonResult.remind("记录已审核过,不能重复审核",log);
                return;
            }

            Merchant supplierMerchant = merchantRepository.findOne(marketMerchantCooperationRecord.getSupplierMerchantId());
            if (supplierMerchant == null) {
                jsonResult.remind("供应商不存在",log);
                return;
            }

            Merchant distributorMerchant = merchantRepository.findOne(marketMerchantCooperationRecord.getDistributorMerchantId());
            if (distributorMerchant == null) {
                jsonResult.remind("分销商不存在",log);
                return;
            }

            marketMerchantCooperationRecord.setStatus(MarketMerchantCooperationStatus.valueOf(marketMerchantCooperationRecordDto.getStatus()));
            marketMerchantCooperationRecordRepository.save(marketMerchantCooperationRecord);

            MarketMerchantCooperation marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(userInfoDto.merchant.getId(), marketMerchantCooperationRecord.getDistributorMerchantId(), MarketMerchantCooperationStatus.REFUSE);
            if (marketMerchantCooperation == null) {
                marketMerchantCooperation = new MarketMerchantCooperation();
            }
            marketMerchantCooperation.setSupplierMerchantId(supplierMerchant.getId());
            marketMerchantCooperation.setSupplierMallId(supplierMerchant.getMallId());
            marketMerchantCooperation.setDistributorMerchantId(distributorMerchant.getId());
            marketMerchantCooperation.setDistributorMallId(distributorMerchant.getMallId());
            marketMerchantCooperation.setStatus(marketMerchantCooperationRecord.getStatus());
            marketMerchantCooperationRepository.save(marketMerchantCooperation);

            // 分销商申请成功消息
            if (MarketMerchantCooperationStatus.valueOf(marketMerchantCooperationRecordDto.getStatus()) == MarketMerchantCooperationStatus.PASS) {
                MarketMerchantCooperationMessage distributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                distributorMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
                distributorMarketMerchantCooperationMessage.setTitle("审核通过");
                distributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，供应商%s已通过您的分销请求，您可以去分销市场分销该商户的产品！", supplierMerchant.getName()));
                marketMerchantCooperationMessageRepository.save(distributorMarketMerchantCooperationMessage);


                // 新增合作分销商 发送对象 供应商
                MarketMerchantCooperationMessage newSupplierMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                newSupplierMarketMerchantCooperationMessage.setMerchantId(supplierMerchant.getId());
                newSupplierMarketMerchantCooperationMessage.setTitle("新增合作分销商");
                newSupplierMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您与分销商%s已达成分销合作关系。", distributorMerchant.getName()));
                marketMerchantCooperationMessageRepository.save(newSupplierMarketMerchantCooperationMessage);

                // 新增合作供应商 发送对象 分销商
                MarketMerchantCooperationMessage newDistributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                newDistributorMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
                newDistributorMarketMerchantCooperationMessage.setTitle("新增合作供应商");
                newDistributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您与供应商%s已达成分销合作关系。", supplierMerchant.getName()));
                marketMerchantCooperationMessageRepository.save(newDistributorMarketMerchantCooperationMessage);
            } else if (MarketMerchantCooperationStatus.valueOf(marketMerchantCooperationRecordDto.getStatus()) == MarketMerchantCooperationStatus.REFUSE) {
                MarketMerchantCooperationMessage distributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                distributorMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
                distributorMarketMerchantCooperationMessage.setTitle("审核失败");
                distributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您提交的与%s供应商分销合作申请已被拒绝。", supplierMerchant.getName()));
                marketMerchantCooperationMessageRepository.save(distributorMarketMerchantCooperationMessage);
            }

        };
        return doing.go(userInfoDto,request,objectMapper, log);
    }

    /**
     * @api {post} /market/merchant/cooperation/record_save 商家合作管理 申请记录 保存
     * @apiGroup market_merchant_cooperation_record
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} supplierMerchantId <code>必须参数</code> 供应商 id
     *
     * @apiSuccess {String} type 类型
     * @apiSuccess {String} status 状态 WAIT("待审核"), PASS("审核通过"),REFUSE("拒绝")
     * @apiSuccess {String} toMerchantName 目标商家名称
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     * }
     *
     */
    @Transactional
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_RECORD_SAVE, method = RequestMethod.POST)
    public JsonResult recordSave(@RequestBody MarketMerchantCooperationRecordDto marketMerchantCooperationRecordDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (marketMerchantCooperationRecordDto.getSupplierMerchantId() == null) {
                jsonResult.errorParam(MarketMerchantCooperationRecord.CHECK_SUPPLIER_MERCHANT_ID_IS_NOT_NULL,log);
                return;
            }
            if(marketMerchantCooperationRecordDto.getSupplierMerchantId() == userInfoDto.merchant.getId()){
                jsonResult.remind("不能向自己申请",log);
                return;
            }


            MarketMerchantCooperation marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(marketMerchantCooperationRecordDto.getSupplierMerchantId(), userInfoDto.merchant.getId(),  MarketMerchantCooperationStatus.REFUSE);

            if (marketMerchantCooperation != null && marketMerchantCooperation.getStatus() == MarketMerchantCooperationStatus.PASS) {
                jsonResult.remind("供应商已是合作关系",log);
                return;
            }
            if (marketMerchantCooperation != null && marketMerchantCooperation.getStatus() == MarketMerchantCooperationStatus.WAIT) {
                jsonResult.remind("您的申请已提交供应商,请耐心等待。",log);
                return;
            }


            Merchant supplierMerchant = merchantRepository.findOne(marketMerchantCooperationRecordDto.getSupplierMerchantId());
            if (supplierMerchant == null) {
                jsonResult.remind("申请的供应商不存在",log);
                return;
            }

            UserInfo distributorUserInfo = userInfoRepository.findOne(userInfoDto.id);

            // 申请记录
            Merchant distributorMerchant = merchantRepository.findOne(userInfoDto.merchant.getId());

            MarketMerchantCooperationRecord marketMerchantCooperationRecord = marketMerchantCooperationRecordRepository.findByDistributorMerchantIdAndSupplierMerchantIdAndStatus(userInfoDto.merchant.getId(), marketMerchantCooperationRecordDto.getSupplierMerchantId(), MarketMerchantCooperationStatus.WAIT);
            if(marketMerchantCooperationRecord != null){
                jsonResult.remind("您已经申请过了,请等待审核",log);
                return;
            }

            marketMerchantCooperationRecord = new MarketMerchantCooperationRecord();
            marketMerchantCooperationRecord.setDistributorMallId(userInfoDto.mall.getId());
            marketMerchantCooperationRecord.setDistributorMerchantId(distributorMerchant.getId());
            marketMerchantCooperationRecord.setDistributorMerchantIntro(distributorMerchant.getIntro());
            marketMerchantCooperationRecord.setDistributorMerchantName(distributorMerchant.getName());
            marketMerchantCooperationRecord.setDistributorUserInfoMobile(distributorUserInfo.getMobile());
            marketMerchantCooperationRecord.setDistributorUserInfoRealName(distributorUserInfo.getRealName());
            marketMerchantCooperationRecord.setDistributorUserInfoEmail(distributorUserInfo.getEmail());

            Mall supplierMall = mallRepository.findOne(supplierMerchant.getMallId());
            UserInfo supplierUserInfo = userInfoRepository.findOne(supplierMerchant.getUserInfoId());

            marketMerchantCooperationRecord.setSupplierMerchantId(supplierMerchant.getId());
            marketMerchantCooperationRecord.setSupplierMallId(supplierMall.getId());
            marketMerchantCooperationRecord.setSupplierMerchantIntro(supplierMerchant.getIntro());
            marketMerchantCooperationRecord.setSupplierMerchantName(supplierMerchant.getName());
            marketMerchantCooperationRecord.setSupplierUserInfoEmail(supplierUserInfo.getEmail());
            marketMerchantCooperationRecord.setSupplierUserInfoMobile(supplierUserInfo.getMobile());
            marketMerchantCooperationRecord.setSupplierUserInfoRealName(supplierUserInfo.getRealName());

            marketMerchantCooperationRecord.setStatus(MarketMerchantCooperationStatus.WAIT);

            marketMerchantCooperationRecordRepository.save(marketMerchantCooperationRecord);

            // 插入合作关系 为待审核
            if (marketMerchantCooperation == null) {
                marketMerchantCooperation = new MarketMerchantCooperation();
            }
            marketMerchantCooperation.setSupplierMerchantId(supplierMerchant.getId());
            marketMerchantCooperation.setSupplierMallId(supplierMerchant.getMallId());
            marketMerchantCooperation.setDistributorMerchantId(distributorMerchant.getId());
            marketMerchantCooperation.setDistributorMallId(distributorMerchant.getMallId());
            marketMerchantCooperation.setStatus(MarketMerchantCooperationStatus.WAIT);
            marketMerchantCooperationRepository.save(marketMerchantCooperation);


            // 分销商申请成功消息
            MarketMerchantCooperationMessage distributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
            distributorMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
            distributorMarketMerchantCooperationMessage.setTitle("申请成功");
            distributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您提交的与%s供应商分销合作申请已成功提交，请耐心等候审核！", supplierMerchant.getName()));
            marketMerchantCooperationMessageRepository.save(distributorMarketMerchantCooperationMessage);

            // 供应商待审核消息
            MarketMerchantCooperationMessage supplierMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
            supplierMarketMerchantCooperationMessage.setMerchantId(supplierMerchant.getId());
            supplierMarketMerchantCooperationMessage.setTitle("待审核");
            supplierMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，%s申请和您达成分销合作关系，请尽快审核。", distributorMerchant.getName()));
            marketMerchantCooperationMessageRepository.save(supplierMarketMerchantCooperationMessage);

        };
        return doing.go(userInfoDto,request,objectMapper, log);
    }


}
